<template>
  <div class="batch-card card" :class="[cardStatusClass, { 'flash-conflict': isFlashing }]">
    <!-- 上传遮罩 -->
    <UploadOverlay
      :visible="isUploading"
      :batch-name="batch.name"
      :batch-logo="getBrandLogo(batch.brand)"
      :upload-progress="uploadProgress"
    />
    <div class="batch-info-container">
      <div class="batch-logo-large">
        <img :src="getBrandLogo(batch.brand)" :alt="batch.brand" class="brand-logo-img-large" />
      </div>

      <div class="batch-info-content">
        <div class="batch-header">
          <div class="batch-name-info">
            <div class="batch-name-row">
              <h3 class="batch-name">{{ batch.name }}</h3>
              <button
                class="icon-btn"
                title="编辑"
                @click="$emit('edit', batch)"
                :disabled="isImporting || isUploading"
              >
                <EditIcon :size="16" />
              </button>
            </div>
            <div class="batch-time">
              <!-- 导入进度条 -->
              <div v-if="showImportProgress" class="import-progress-container">
                <div class="import-progress-bar">
                  <div
                    class="import-progress-fill"
                    :class="{ stopped: batch.importStatus === 'stopped' }"
                    :style="{ width: batch.importProgress + '%' }"
                  ></div>
                </div>
                <div class="import-progress-text">{{ batch.importProgress }}%</div>
                <button
                  v-if="batch.importStatus === 'importing'"
                  class="stop-btn"
                  title="停止导入"
                  @click="$emit('stop-import', batch.id)"
                >
                  <StopIcon :size="14" />
                </button>
              </div>
              <!-- 导入时间 -->
              <div v-else-if="batch.importTime" class="import-time">
                导入时间：{{ batch.importTime }}
              </div>
              <!-- 默认显示 -->
              <div v-else class="import-time">导入时间：--</div>
            </div>
          </div>
        </div>

        <div class="batch-progress">
          <div class="progress-item">
            <div class="progress-label">匹配进度</div>
            <div class="progress-bar">
              <div class="progress-fill" :style="{ width: batch.matchingProgress + '%' }"></div>
            </div>
            <div class="progress-text">{{ batch.matchingProgress }}%</div>
          </div>

          <div class="progress-item">
            <div class="progress-label">向量进度</div>
            <div class="progress-bar">
              <div class="progress-fill" :style="{ width: batch.vectorProgress + '%' }"></div>
            </div>
            <div class="progress-text">{{ batch.vectorProgress }}%</div>
          </div>
        </div>
      </div>
    </div>

    <div class="batch-anomalies">
      <div class="stats-group">
        <div class="stats-title">基础统计</div>
        <div class="stats-items">
          <div class="stat-item">
            <span class="stat-label">信息总数：</span>
            <span class="stat-count primary">{{ batch.totalInfo || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">图片总数：</span>
            <span class="stat-count primary">{{ batch.totalImages || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">识别款式：</span>
            <span class="stat-count primary">{{ batch.identifiedStyles || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">识别颜色：</span>
            <span class="stat-count primary">{{ batch.identifiedColors || 0 }}</span>
          </div>
        </div>
      </div>
      <div class="stats-group clickable" @click="openAnomalyDialog">
        <div class="stats-title">异常情况</div>
        <div class="stats-items">
          <div class="stat-item">
            <span class="stat-label">命名异常：</span>
            <span class="stat-count warning">{{ batch.anomalies?.naming || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">仅图片：</span>
            <span class="stat-count warning">{{ batch.anomalies?.emptyImage || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">仅信息：</span>
            <span class="stat-count warning">{{ batch.anomalies?.emptyInfo || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">放弃：</span>
            <span class="stat-count warning">{{ batch.anomalies?.abandoned || 0 }}</span>
          </div>
        </div>
      </div>
    </div>

    <div class="batch-actions">
      <div class="left-actions">
        <button
          class="btn"
          :class="getEnterMatchingButtonClass()"
          @click="$emit('enter-matching', batch.id)"
          :disabled="isImporting || isUploading || !canEnterMatching"
        >
          <EnterMatchingIcon :size="14" />
          进入匹配
        </button>
        <button
          class="btn"
          :class="getImportButtonClass()"
          @click="$emit('import', batch.id)"
          :disabled="isImporting || isUploading || !canImport"
        >
          <ImportIcon :size="14" />
          导入
        </button>
        <button
          class="btn"
          :class="getUpdateVectorsButtonClass()"
          @click="handleUpdateVectors"
          :disabled="isImporting || isUploading || !canUpdateVectors || isUpdateVectorsProcessing"
        >
          <UpdateVectorsIcon :size="14" />
          更新向量库
        </button>
      </div>
      <div class="right-actions">
        <button
          class="btn"
          :class="getArchiveButtonClass()"
          @click="handleArchive"
          :disabled="isImporting || isUploading || !canArchive || isArchiveProcessing"
        >
          <ArchiveIcon :size="14" />
          {{ getArchiveButtonText() }}
        </button>
      </div>
    </div>
    <button
      class="icon-btn delete-float"
      title="删除"
      @click="$emit('delete', batch)"
      :disabled="isImporting || isUploading"
    >
      <DeleteIcon :size="16" />
    </button>

    <!-- 异常详情弹窗 -->
    <AnomalyDetailDialog
      :visible="anomalyDialogVisible"
      :batch-id="batch.id"
      :batch="batch"
      :brands="brands"
      @close="closeAnomalyDialog"
    />
  </div>
</template>

<script>
import { computed, ref, onMounted, onUnmounted } from 'vue'
import { generateLogoPlaceholder } from '../utils/logoPlaceholder'
import { createBatchButtonManager, getButtonClass } from '../utils/buttonStateManager'
import {
  EditIcon,
  DeleteIcon,
  ImportIcon,
  UpdateVectorsIcon,
  ArchiveIcon,
  EnterMatchingIcon,
  StopIcon,
} from './icons'
import UploadOverlay from './UploadOverlay.vue'
import AnomalyDetailDialog from './AnomalyDetailDialog.vue'

export default {
  name: 'BatchCard',
  components: {
    UploadOverlay,
    AnomalyDetailDialog,
    EditIcon,
    DeleteIcon,
    ImportIcon,
    UpdateVectorsIcon,
    ArchiveIcon,
    EnterMatchingIcon,
    StopIcon,
  },
  props: {
    batch: {
      type: Object,
      required: true,
    },
    brands: {
      type: Array,
      default: () => [],
    },
    isUploading: {
      type: Boolean,
      default: false,
    },
    uploadProgress: {
      type: Object,
      default: () => ({}),
    },
    isFlashing: {
      type: Boolean,
      default: false,
    },
  },
  emits: ['enter-matching', 'edit', 'import', 'update-vectors', 'archive', 'delete', 'stop-import'],
  setup(props, { emit }) {
    const anomalyDialogVisible = ref(false)
    const buttonManager = ref(null)

    // 按钮处理状态
    const isUpdateVectorsProcessing = computed(() => {
      return buttonManager.value?.isProcessing(`update-vectors_${props.batch.id}`) || false
    })

    const isArchiveProcessing = computed(() => {
      return buttonManager.value?.isProcessing(`archive_${props.batch.id}`) || false
    })

    // 初始化按钮管理器
    onMounted(() => {
      buttonManager.value = createBatchButtonManager(props.batch.id)
    })

    // 清理资源
    onUnmounted(() => {
      if (buttonManager.value) {
        buttonManager.value.clear()
      }
    })

    // 获取品牌Logo
    const getBrandLogo = brand => {
      if (!brand) return generateLogoPlaceholder('Unknown')
      const brandData = props.brands.find(b => b.name === brand)
      return brandData?.logo || generateLogoPlaceholder(brand)
    }

    // 显示导入进度
    const showImportProgress = computed(() => {
      const shouldShow =
        props.batch.importStatus === 'importing' ||
        (props.batch.importStatus === 'stopped' && props.batch.importProgress > 0)
      return shouldShow
    })

    // 计算是否正在导入
    const isImporting = computed(() => {
      return props.batch.status === 'importing' && props.batch.importStatus === 'importing'
    })

    // 卡片状态类
    const cardStatusClass = computed(() => {
      const status = props.batch.status
      const classes = []

      if (isImporting.value) {
        classes.push('importing')
      }

      if (props.isUploading) {
        classes.push('uploading')
      }

      switch (status) {
        case 'new':
          classes.push('status-new')
          break
        case 'import_completed':
          classes.push('status-import-completed')
          break
        case 'matching_completed':
          classes.push('status-matching-completed')
          break
        case 'vector_completed':
          classes.push('status-vector-completed')
          break
        case 'archived':
          classes.push('status-archived')
          break
        case 'import_stopped':
          classes.push('status-import-stopped')
          break
        case 'importing':
          classes.push('status-importing')
          break
      }

      return classes
    })

    // 按钮状态计算
    const canEnterMatching = computed(() => {
      return ['import_completed', 'matching_completed', 'vector_completed', 'archived'].includes(
        props.batch.status
      )
    })

    const canImport = computed(() => {
      // 导入按钮在所有非导入中状态下都可用
      return props.batch.importStatus !== 'importing'
    })

    const canUpdateVectors = computed(() => {
      return ['matching_completed'].includes(props.batch.status)
    })

    const canArchive = computed(() => {
      return ['import_completed', 'vector_completed', 'archived'].includes(props.batch.status)
    })

    // 按钮样式方法
    const getEnterMatchingButtonClass = () => {
      if (['import_completed'].includes(props.batch.status)) {
        return 'btn-primary'
      }
      return ''
    }

    const getUpdateVectorsButtonClass = () => {
      const baseClass = props.batch.status === 'matching_completed' ? 'btn-primary' : ''
      return getButtonClass(
        `update-vectors_${props.batch.id}`,
        isUpdateVectorsProcessing.value,
        baseClass
      )
    }

    const getImportButtonClass = () => {
      if (['new', 'import_stopped'].includes(props.batch.status)) {
        return 'btn-primary'
      }
      return ''
    }

    const getArchiveButtonClass = () => {
      const baseClass = ['import_completed', 'vector_completed', 'archived'].includes(
        props.batch.status
      )
        ? 'btn-primary'
        : ''
      return getButtonClass(`archive_${props.batch.id}`, isArchiveProcessing.value, baseClass)
    }

    const getArchiveButtonText = () => {
      return props.batch.status === 'archived' ? '恢复' : '归档'
    }

    // 按钮处理函数
    const handleUpdateVectors = async () => {
      if (!buttonManager.value) return

      buttonManager.value.debounce(`update-vectors_${props.batch.id}`, async () => {
        try {
          buttonManager.value.setProcessing(`update-vectors_${props.batch.id}`, true)

          // 直接调用API
          const { updateBatchVectors } = await import('../api/batchApi')
          const res = await updateBatchVectors(props.batch.id)
          console.log('更新向量库结果:', res)

          if (res.code === 200) {
            // 使用Element Plus的消息提示
            const { ElMessage } = await import('element-plus')
            ElMessage.success(res.message || '更新向量库成功')
            // 发出事件通知父组件刷新数据
            emit('update-vectors', props.batch.id)
          } else {
            const { ElMessage } = await import('element-plus')
            ElMessage.error(res.message || '更新向量库失败')
          }
        } catch (error) {
          console.error('更新向量库失败:', error)
          const { ElMessage } = await import('element-plus')
          ElMessage.error('更新向量库失败')
        } finally {
          buttonManager.value.setProcessing(`update-vectors_${props.batch.id}`, false)
        }
      })
    }

    const handleArchive = async () => {
      if (!buttonManager.value) return

      buttonManager.value.debounce(`archive_${props.batch.id}`, async () => {
        try {
          buttonManager.value.setProcessing(`archive_${props.batch.id}`, true)

          // 根据批次状态决定调用归档还是取消归档API
          const { archiveBatch, unarchiveBatch } = await import('../api/batchApi')
          let res

          if (props.batch.status === 'archived') {
            // 如果批次已归档，则调用取消归档API
            res = await unarchiveBatch(props.batch.id)
          } else {
            // 否则调用归档API
            res = await archiveBatch(props.batch.id)
          }

          console.log('归档操作结果:', res)

          if (res.code === 200) {
            const { ElMessage } = await import('element-plus')
            ElMessage.success(res.message || '归档操作成功')
            // 发出事件通知父组件刷新数据
            emit('archive', props.batch.id)
          } else {
            const { ElMessage } = await import('element-plus')
            ElMessage.error(res.message || '归档操作失败')
          }
        } catch (error) {
          console.error('归档操作失败:', error)
          const { ElMessage } = await import('element-plus')
          ElMessage.error('归档操作失败')
        } finally {
          buttonManager.value.setProcessing(`archive_${props.batch.id}`, false)
        }
      })
    }

    // 异常弹窗相关函数
    const openAnomalyDialog = () => {
      console.log('异常弹窗被点击，批次ID:', props.batch.id)
      anomalyDialogVisible.value = true
    }

    const closeAnomalyDialog = () => {
      anomalyDialogVisible.value = false
    }

    return {
      getBrandLogo,
      showImportProgress,
      isImporting,
      cardStatusClass,
      canEnterMatching,
      canImport,
      canUpdateVectors,
      canArchive,
      getEnterMatchingButtonClass,
      getImportButtonClass,
      getUpdateVectorsButtonClass,
      getArchiveButtonClass,
      getArchiveButtonText,
      anomalyDialogVisible,
      openAnomalyDialog,
      closeAnomalyDialog,
      isFlashing: computed(() => props.isFlashing),
      // 按钮处理状态
      isUpdateVectorsProcessing,
      isArchiveProcessing,
      // 按钮处理函数
      handleUpdateVectors,
      handleArchive,
    }
  },
}
</script>

<style scoped>
/* 引入按钮动画样式 */
@import '../styles/button-animations.css';

.batch-card {
  padding: 12px;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  background: white;
  transition: all 0.2s;
  position: relative;
  height: fit-content;
}

.upload-progress-bar .progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #3498db, #2980b9);
  transition: width 0.3s ease;
}

.upload-progress-text {
  font-size: 12px;
  color: #333;
  font-weight: 500;
  text-align: center;
}

/* 左侧色带 */
.batch-card::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 6px;
  border-top-left-radius: var(--border-radius);
  border-bottom-left-radius: var(--border-radius);
  opacity: 0.65;
}

.batch-card:hover {
  border-color: var(--primary-color);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.batch-card.importing,
.batch-card.uploading {
  opacity: 0.8;
}

.batch-card.importing .batch-actions .btn:not(.stop-btn),
.batch-card.uploading .batch-actions .btn:not(.stop-btn) {
  opacity: 0.5;
  cursor: not-allowed;
  pointer-events: none;
}

.batch-card.importing .icon-btn:not(.stop-btn),
.batch-card.uploading .icon-btn:not(.stop-btn) {
  opacity: 0.5;
  cursor: not-allowed;
  pointer-events: none;
}

/* 禁用按钮样式 */
.batch-actions .btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  background: #f5f5f5;
  border-color: #d9d9d9;
  color: #bfbfbf;
}

.batch-actions .btn:disabled:hover {
  background: #f5f5f5;
  border-color: #d9d9d9;
  color: #bfbfbf;
}

.icon-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  color: #bfbfbf;
}

.icon-btn:disabled:hover {
  background: transparent;
  color: #bfbfbf;
}

/* 冲突闪烁动画 */
@keyframes flash-conflict {
  0% {
    border-color: #d9d9d9;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    background: white;
    transform: scale(1);
  }
  25% {
    border-color: #ff4d4f;
    box-shadow: 0 0 0 8px rgba(255, 77, 79, 0.3);
    background: #fff5f5;
    transform: scale(1.02);
  }
  50% {
    border-color: #ff4d4f;
    box-shadow: 0 0 0 12px rgba(255, 77, 79, 0.4);
    background: #ffe6e6;
    transform: scale(1.01);
  }
  75% {
    border-color: #ff4d4f;
    box-shadow: 0 0 0 8px rgba(255, 77, 79, 0.3);
    background: #fff5f5;
    transform: scale(1.02);
  }
  100% {
    border-color: #d9d9d9;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    background: white;
    transform: scale(1);
  }
}

.batch-card.flash-conflict {
  animation: flash-conflict 1.2s ease-in-out 3;
  animation-fill-mode: both;
}

/* 状态背景色 */
.batch-card.status-new {
  background: #f8f9fa;
  /* 新建/停止：比纯白更柔和 */
}

.batch-card.status-new::before {
  background: #cbd5e1;
  /* 新建状态色带 */
}

.batch-card.status-import-completed {
  background: #f3e8d1;
  /* 导入完成：较导入中略深 */
}

.batch-card.status-import-completed::before {
  background: #d7be8a;
  /* 导入完成色带 */
}

.batch-card.status-matching-completed {
  background: #dceaf5;
  /* 匹配完成：中浅蓝灰 */
}

.batch-card.status-matching-completed::before {
  background: #9db9d3;
  /* 匹配完成色带 */
}

.batch-card.status-vector-completed {
  background: #cfe5d8;
  /* 向量完成：更重的灰绿（完成态最"重"） */
}

.batch-card.status-vector-completed::before {
  background: #7eb49a;
  /* 向量完成色带 */
}

.batch-card.status-archived {
  background: #f1f3f5;
  /* 归档：中性浅灰 */
}

.batch-card.status-archived::before {
  background: #cbd5e1;
  /* 归档状态色带 */
}

.batch-card.status-import-stopped {
  background: #f8f9fa;
  /* 与新建一致，表示停滞、未动 */
}

.batch-card.status-import-stopped::before {
  background: #cbd5e1;
  /* 导入停止色带 */
}

.batch-card.status-importing {
  background: #f7f0d9;
  /* 导入中：浅米黄（L较高） */
}

.batch-card.status-importing::before {
  background: #e0cda0;
  /* 导入中色带 */
}

.batch-info-container {
  display: flex;
  gap: 12px;
  margin-bottom: 8px;
}

.batch-logo-large {
  width: 90px;
  height: 90px;
  flex-shrink: 0;
}

.brand-logo-img-large {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 6px;
  border: 1px solid var(--border-color);
}

.batch-info-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.batch-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.batch-name-info {
  flex: 1;
}

.batch-name-row {
  display: flex;
  align-items: center;
  gap: 6px;
}

.batch-name {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-color);
  margin: 0 0 2px 0;
}

.batch-time {
  font-size: 12px;
  color: var(--text-secondary);
}

.import-progress-container {
  display: flex;
  align-items: center;
  gap: 6px;
}

.import-progress-bar {
  flex: 1;
  height: 4px;
  background: #f0f0f0;
  border-radius: 2px;
  overflow: hidden;
}

.import-progress-fill {
  height: 100%;
  background: var(--primary-color);
  transition: width 0.3s ease;
}

.import-progress-fill.stopped {
  background: #999;
}

.import-progress-text {
  font-size: 11px;
  color: var(--text-secondary);
  min-width: 30px;
}

.stop-btn {
  color: #ff4d4f;
  background: #fff1f0;
  border: 1px solid #ff4d4f;
  padding: 2px;
  border-radius: 3px;
  cursor: pointer;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  font-weight: bold;
}

.stop-btn:hover {
  background: #ff4d4f;
  color: white;
  transform: scale(1.1);
}

.import-time {
  font-size: 12px;
  color: var(--text-secondary);
}

.batch-progress {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.progress-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

.progress-label {
  min-width: 50px;
  font-size: 12px;
  color: var(--text-secondary);
}

.progress-bar {
  flex: 1;
  height: 6px;
  background: #f0f0f0;
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: var(--primary-color);
  transition: width 0.3s ease;
}

/* 不同状态的进度条颜色 */
.batch-card.status-matching-completed .progress-item:first-child .progress-fill {
  background: var(--success-color);
}

.batch-card.status-vector-completed .progress-item:last-child .progress-fill {
  background: var(--success-color);
}

.progress-text {
  min-width: 35px;
  font-size: 12px;
  color: var(--text-secondary);
  text-align: right;
}

.batch-anomalies {
  display: flex;
  gap: 12px;
  margin-bottom: 8px;
  padding: 8px;
  background: #f8f9fa;
  border-radius: var(--border-radius);
}

.stats-group {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.stats-title {
  font-size: 12px;
  font-weight: 600;
  color: var(--text-color);
  margin-bottom: 4px;
}

.stats-items {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 4px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.stat-label {
  font-size: 11px;
  color: var(--text-secondary);
  white-space: nowrap;
}

.stat-count {
  font-size: 12px;
  font-weight: 600;
  min-width: 20px;
  text-align: right;
}

.stat-count.primary {
  color: var(--primary-color);
}

.stat-count.warning {
  color: #faad14;
  /* Warning color */
}

.clickable {
  cursor: pointer;
  transition: all 0.2s;
}

.clickable:hover {
  background-color: #f8f9fa;
  border-radius: 6px;
  padding: 8px;
  margin: -8px;
}

.batch-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
}

.left-actions,
.right-actions {
  display: flex;
  gap: 6px;
}

.batch-actions .btn {
  padding: 6px 10px;
  font-size: 12px;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.icon-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  border: none;
  background: transparent;
  color: var(--text-secondary);
  border-radius: 4px;
  cursor: pointer;
}

.icon-btn:hover {
  background: #f5f5f5;
  color: var(--primary-color);
}

.delete-float {
  position: absolute;
  top: 6px;
  right: 6px;
  color: var(--error-color);
}

.delete-float:hover {
  background: #fff1f0;
  color: #ff4d4f;
}

@media (max-width: 768px) {
  .batch-info-container {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }

  .batch-logo-large {
    width: 60px;
    height: 60px;
  }

  .batch-anomalies {
    flex-direction: column;
    gap: 8px;
  }

  .batch-actions {
    flex-direction: column;
  }
}
</style>
